import { useEffect, useRef, useState } from 'react'
import { getDayLots, getDayLotsRecord, getDayLotsInfo } from '../../../api/active'
import { useNavigate } from 'react-router-dom'
import './index.less'
import { unZipLottieFile } from '../../../utils/util'
import Lottie from 'lottie-web'
import { InfiniteScroll, Modal, NoticeBar, Toast } from 'antd-mobile'
import { GetUserInfo } from '../../../api/mine'

// import img from '../../../images/draw_lots/long_bg.png';

// https://cdn.aimengtec.com/h5_static/lots_main_animation.zip
let isDown = false
// const lot_price = 10;
// 2：礼物 4：头像框 5：气泡框 6：进场特效
export default function DrawLots() {
  const navigate = useNavigate()
  const [selectNum, setSelectNum] = useState(1)
  const [activeInfo, setActiveInfo] = useState({ id: 0, mizuan: 0 })
  const [userinfo, setUserinfo] = useState({ mizuan: 0 })
  const [recordList, setRecordList] = useState([])
  const [gift, setGift] = useState([])
  const [animation, setAnimation] = useState(false)
  const ref = useRef()

  const [smallVisible, setSmallVisible] = useState(false)
  const [ruleVisible, setRuleVisible] = useState(false)

  useEffect(() => {
    getRecordList()
    Toast.show({
      icon: 'loading',
      maskClickable: false,
      duration: 0
    })
    getDayLotsInfo({
      type: 6
    })
      .then((res) => {
        // console.log(res);
        if (res.data?.list?.length) {
          setActiveInfo(res.data?.list[0])
        }
        GetUserInfo()
          .then((res) => {
            setUserinfo(res.data)
          })
          .finally(() => {
            setTimeout(() => {
              Toast.clear()
            }, 200)
          })
      })
      .finally(() => {
        initAnimation()
      })
  }, [])

  const initAnimation = () => {
    if (!ref?.current && !isDown) {
      isDown = true
      Toast.show({
        content: '加载中~',
        icon: 'loading',
        maskClickable: false
      })
      // unZipLottieFile('https://cdn.aimengtec.com/h5_static/lots_main_animation.zip').then(res => {
      //     console.log(res);
      //     Toast.clear()
      //     ref.current = Lottie.loadAnimation({
      //         container: document.getElementById("lottie"),
      //         renderer: "svg",
      //         loop: false,
      //         autoplay: false,
      //         // 这里要修改为这个
      //         assetsPath: `blob:${window.location.origin}/`,
      //         animationData: res.json,
      //     });
      //     ref.current.addEventListener('complete', (r) => {
      //         console.log('complete', r);
      //         getRecordList();
      //         setAnimation(false); // 结束
      //         setTimeout(() => {
      //             Lottie.stop();
      //         }, 100);
      //     })
      // })
    }
  }

  const handleClick = () => {
    if (!animation) {
      // setGift(null);
      Toast.show({
        icon: 'loading',
        maskClickable: false,
        duration: 0
      })
      getDayLots({
        box_id: activeInfo.id,
        nums: selectNum
      }).then((res) => {
        console.log(res)
        Toast.clear()
        setAnimation(true) // 开始动画
        Lottie.play()
        setGift(res.data)
        GetUserInfo().then((res) => {
          setUserinfo(res.data)
        })
      })
    } else {
      Toast.show({
        content: '等待抽奖结束~'
      })
    }
  }

  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const getRecordList = async () => {
    try {
      const res = await getDayLotsRecord({ page })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  const onConfirm = () => {
    setSmallVisible(false)
    if (Number(userinfo.mizuan) >= +activeInfo.mizuan * selectNum) {
      handleClick()
    } else {
      navigate('/recharge')
    }
  }

  const onCancel = () => {
    setSmallVisible(false)
  }

  return (
    <div className="draw_lots_wrap">
      <div className="rule_btn" onClick={() => setRuleVisible(true)}>
        规则
      </div>
      <div className="tips">
        <NoticeBar
          content={'理性参与游戏活动，禁止一切赌博性质行为，谨防上当受骗，杜绝违法犯罪，珍享游戏趣味。'}
          color="alert"
          icon={null}
        />
      </div>
      <div className={`lottie ${gift?.length && !animation ? 'hidden' : ''}`} id="lottie"></div>
      <div className="lots_cover">
        <div className="btn_group">
          <div className={`draw_btn ${gift?.length ? 'continue' : ''}`} onClick={() => setSmallVisible(true)}></div>
          <div className={`btn_num ${selectNum === 1 ? 'active' : ''}`} onClick={() => setSelectNum(1)}></div>
          <div className={`btn_num ${selectNum === 10 ? 'active' : ''}`} onClick={() => setSelectNum(10)}></div>
          <div className={`btn_num ${selectNum === 100 ? 'active' : ''}`} onClick={() => setSelectNum(100)}></div>
        </div>
        <div className="record_tit">—· 抽签记录 ·—</div>
        <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
        {/* <div className="record_content">
                    {
                        recordList?.map((item) => (
                            <div className="item" key={item.create_time}>
                                <div className="img">
                                    <img src={item.img} alt="" />
                                </div>
                                <div className="name ellipsis1">{item.note}</div>
                                <div className="price">{item.mizuan}{window.baseConfig.coin_name}</div>
                                <div className={`tag type_${item?.award_type || 2}`}></div>
                            </div>
                        ))
                    }
                </div> */}
      </div>
      <div className="scroll">
        {gift?.length && !animation ? (
          // gift.map((item) => (
          //     <div className="gift_box">
          //         <div className="img">
          //             <img src={item.img} alt="" />
          //         </div>
          //         <div className="name ellipsis1">{item.name}</div>
          //         <div className="price">{item.price}{window.baseConfig.coin_name}</div>
          //     </div>
          // ))
          <div className={`record_content ${gift?.length <= 6 ? '' : 'column'}`}>
            {gift?.map((item) => (
              <div className="item" key={item.id}>
                <div className="img">
                  <img src={item.img} alt="" />
                </div>
                <div className="name ellipsis1">{item.name}</div>
                <div className="price">
                  {item.price}
                  {window.baseConfig.coin_name}
                </div>
                <div className={`tag type_${item?.award_type || 2}`}></div>
                <div className={`nums ${item?.nums <= 1 ? 'none' : ''}`}>
                  <span>x{item?.nums}</span>
                </div>
              </div>
            ))}
          </div>
        ) : null}
      </div>

      <Modal
        className="dropdown"
        visible={smallVisible}
        content={
          <div className="modal_lot">
            <div className="txt">
              {Number(userinfo.mizuan) >= +activeInfo.mizuan * selectNum
                ? `是否花费${activeInfo.mizuan * selectNum}${window.baseConfig.coin_name}抽签`
                : `${window.baseConfig.coin_name}不足，是否充值`}
            </div>
            <div className="btn_group">
              <div className="cancel btn" onClick={onCancel}>
                取消
              </div>
              <div className="confirm btn" onClick={onConfirm}>
                确认
              </div>
            </div>
          </div>
        }
      ></Modal>
      <Modal
        visible={ruleVisible}
        closeOnMaskClick={true}
        onClose={() => setRuleVisible(false)}
        className="rule"
        content={
          <div className="modal_rule">
            <div className="content">
              <p className="t">每日上上签活动规则</p>
              <div className="con">
                <p>
                  1、  参与“每日上上签”活动消耗20{window.baseConfig.coin_name}
                  即可抽一签，每次抽签后，即可直接获得相应的奖品，抽的的奖品可在"抽签记录"里面查看。
                </p>
                <p>
                  2、  "每日上上签"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
                  {window.baseConfig.coin_name}、现金、不可再次交易; 您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为。
                </p>
                <p>
                  3、  利用漏洞或者是其他非法途径参与本活动，官方有权取消其活动参与资格。{window.baseConfig.package_name}
                  有权清除活动中的非法数据。
                </p>
                <p>4、  活动如有任何疑问请联系{window.baseConfig.package_name}客服。</p>
                <p>
                  5、  活动获得的所有虚拟道具及权益均不可进行转让、交易或变现，{window.baseConfig.package_name}
                  官方有权对任何违规行为进行处理。
                </p>
                <p>在此活动中，APPLE不是赞助者，也没有以任何形式参与活动</p>
              </div>
              <p className="t">奖品详情</p>
              <div className="con">
                <img src={activeInfo.rule_img} alt="" />
              </div>
            </div>
          </div>
        }
      ></Modal>
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      {/* <div className="tit">解救记录</div> */}
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.create_time}>
            <div
              className="item"
              onClick={() => {
                if (item.create_time === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.create_time)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.create_time ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
